/**
 * API调试脚本
 * 用于测试和调试各个模型的API调用
 */

// 测试DeepSeek API
export async function testDeepSeekAPI() {
  console.log('🧪 测试DeepSeek API...')
  
  const apiKey = import.meta.env.VITE_DEEPSEEK_API_KEY
  if (!apiKey) {
    console.log('❌ 未配置 DEEPSEEK API KEY')
    return
  }
  
  const testModels = ['deepseek-reasoner']  // 只测试推理模型（你要的那个）
  
  for (const model of testModels) {
    console.log(`测试模型: ${model}`)
    
    try {
      const response = await fetch('https://api.deepseek.com/v1/chat/completions', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${apiKey}`
        },
        body: JSON.stringify({
          model: model,
          messages: [
            { role: 'user', content: '你好，请简单介绍一下你自己' }
          ],
          max_tokens: 100
        })
      })
      
      if (response.ok) {
        const data = await response.json()
        console.log(`✅ ${model} 成功:`, data.choices[0].message.content)
      } else {
        const error = await response.text()
        console.log(`❌ ${model} 失败 (${response.status}):`, error)
      }
    } catch (error) {
      console.log(`❌ ${model} 网络错误:`, error)
    }
    
    // 添加延迟
    await new Promise(resolve => setTimeout(resolve, 1000))
  }
}

// 测试豆包API
export async function testDoubaoAPI() {
  console.log('🧪 测试豆包 API...')
  
  const apiKey = import.meta.env.VITE_DOUBAO_API_KEY
  if (!apiKey) {
    console.log('❌ 未配置 DOUBAO API KEY')
    return
  }
  
  const testModels = [
    'doubao-seed-1-6-250615'  // 只测试这一个可用的模型
  ]
  
  for (const model of testModels) {
    console.log(`测试模型: ${model}`)
    
    try {
      const response = await fetch('https://ark.cn-beijing.volces.com/api/v3/chat/completions', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${apiKey}`
        },
        body: JSON.stringify({
          model: model,
          messages: [
            { role: 'user', content: '你好，请简单介绍一下你自己' }
          ],
          max_tokens: 100
        })
      })
      
      if (response.ok) {
        const data = await response.json()
        console.log(`✅ ${model} 成功:`, data.choices[0].message.content)
      } else {
        const error = await response.text()
        console.log(`❌ ${model} 失败 (${response.status}):`, error)
      }
    } catch (error) {
      console.log(`❌ ${model} 网络错误:`, error)
    }
    
    // 添加延迟
    await new Promise(resolve => setTimeout(resolve, 1000))
  }
}

// 测试通义千问API
export async function testQwenAPI() {
  console.log('🧪 测试通义千问 API...')
  
  const apiKey = import.meta.env.VITE_QWEN_API_KEY
  if (!apiKey) {
    console.log('❌ 未配置 QWEN API KEY')
    return
  }
  
  const testModels = ['qwen-plus-latest']  // 只测试你要的这一个模型
  
  for (const model of testModels) {
    console.log(`测试模型: ${model}`)
    
    try {
      const response = await fetch('https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${apiKey}`
        },
        body: JSON.stringify({
          model: model,
          messages: [
            { role: 'user', content: '你好，请简单介绍一下你自己' }
          ],
          max_tokens: 100
        })
      })
      
      if (response.ok) {
        const data = await response.json()
        console.log(`✅ ${model} 成功:`, data.choices[0].message.content)
      } else {
        const error = await response.text()
        console.log(`❌ ${model} 失败 (${response.status}):`, error)
      }
    } catch (error) {
      console.log(`❌ ${model} 网络错误:`, error)
    }
    
    // 添加延迟
    await new Promise(resolve => setTimeout(resolve, 1000))
  }
}

// 运行所有测试
export async function runAllAPITests() {
  console.log('🚀 开始API调试测试...\n')
  
  await testDeepSeekAPI()
  console.log('\n' + '='.repeat(50) + '\n')
  
  await testDoubaoAPI()
  console.log('\n' + '='.repeat(50) + '\n')
  
  await testQwenAPI()
  
  console.log('\n✅ 所有API测试完成')
}

// 获取可用模型列表（如果API支持）
export async function getAvailableModels() {
  console.log('🔍 获取可用模型列表...\n')
  
  // DeepSeek支持列出模型
  const deepseekApiKey = import.meta.env.VITE_DEEPSEEK_API_KEY
  if (deepseekApiKey) {
    console.log('DeepSeek可用模型:')
    try {
      const response = await fetch('https://api.deepseek.com/v1/models', {
        headers: {
          'Authorization': `Bearer ${deepseekApiKey}`
        }
      })
      
      if (response.ok) {
        const data = await response.json()
        data.data.forEach((model: any) => {
          console.log(`- ${model.id}`)
        })
      } else {
        console.log('❌ 获取DeepSeek模型列表失败')
      }
    } catch (error) {
      console.log('❌ DeepSeek网络错误:', error)
    }
  }
  
  console.log('\n注意：豆包和通义千问不支持列出模型，需要查看官方文档')
}

// 如果直接运行此文件
if (typeof window === 'undefined') {
  getAvailableModels()
    .then(() => runAllAPITests())
    .catch(console.error)
}